package uc.org.jkas.model;
import org.jkas.core.Model;
import java.util.HashMap;
import java.util.ArrayList;
public class PrivilegesM extends Model
{ 
	public PrivilegesM()
	{
	 primaryKey("privi_id");
	}

	public HashMap<String,String> getByName(String caption)
	{   HashMap<Integer,Object> params=new HashMap<Integer,Object>();
	    params.put(1,caption);
		return this.where("caption=?").prepareRows(params);
	}

	public boolean exists(String caption)
	{return exists(caption,0);
	}

	public boolean exists(String caption,int privi_id)
	{boolean res=false;
	   HashMap<String,String> info=null;
			      this.where(strc("caption='",caption,"'"));
					info=this.getRows();
					if(info!=null && !info.isEmpty())
		             { if(privi_id>0 && privi_id==toInt(info.get("privi_id")))
						 {res=false;}
					     else
						 {
						   res=true;
						 }
		             }
	   return res;
	}

 @SuppressWarnings("unchecked")
	public  HashMap<String,ArrayList> getPrivileges(String[] privis)
	{  HashMap<String,ArrayList> res=new HashMap<String,ArrayList>();
	   HashMap<Integer,Integer> objs=new HashMap<Integer,Integer>();
		ArrayList<HashMap> lists=this.order("parent_id asc,control asc").select();
		ArrayList<Integer> parents=new ArrayList<Integer>();
		ArrayList<Integer> child=null;
	    int parent_id=0;
		int index=-1;
		int i=0;
		HashMap<String,Integer> prinfo=new HashMap<String,Integer>();
		if(privis!=null)
		{
			 for(String priv:privis)
			 {prinfo.put(priv,1);
			 }
		}
		 for(HashMap list:lists)
		  {parent_id=toInt(list.get("parent_id"));
	        if(parent_id>0)
			 {try
				{
			      index=objs.get(parent_id);
				}catch(Exception e)
				{index=-1;
				}
               if(index>-1)
				 {child=(ArrayList<Integer>)lists.get(index).get("child");
		           if(child==null)
				    {child=new ArrayList<Integer>();
				    }
				    child.add(i);
				    lists.get(index).put("child",child);
					if(prinfo.get(list.get("privi_id"))!=null)
					 {lists.get(i).put("sel",1);
					 }
				 }
			 }
			 else
			  {parents.add(i);
			  }
              objs.put(toInt(list.get("privi_id")),i);
			  i++;
		  }

		  res.put("parents",parents);
		  res.put("lists",lists);
		return res;
	}
}